# Copyright (c) HySoP 2011-2024
#
# This file is part of HySoP software.
# See "https://particle_methods.gricad-pages.univ-grenoble-alpes.fr/hysop-doc/"
# for further info.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import sys
import numpy as np
from abc import ABCMeta, abstractmethod
from hysop.constants import default_order, MemoryOrdering, Backend
from hysop.constants import HYSOP_REAL, HYSOP_COMPLEX
from hysop.constants import HYSOP_INTEGER, HYSOP_INDEX, HYSOP_DIM, HYSOP_BOOL
from hysop.tools.misc import prod
from hysop.tools.htypes import check_instance, to_tuple, to_list
from hysop.tools.handle import TaggedObject
from hysop.tools.numerics import (
is_fp,
is_complex,
match_float_type,
match_complex_type,
complex_to_float_dtype,
)
from hysop.core.memory.allocator import AllocatorBase
[docs]
class ArrayBackend(TaggedObject, metaclass=ABCMeta):
"""
Interface of an abstract array backend.
An array backend is a numpy work-alike collection of functions that
performs its computations on arrays on various devices.
Most of exposed functions should work exactly as in numpy,
some default arguments are changed to match HySoP parameters
(default ordering, default floating point type,
default integer type, default device, ...)
All exposed functions are @classmethods, and this class cannot
be instanciated.
Arithmetic methods, when available, should at least support the
broadcasting of scalars.
See this link for more information about numpy routines:
https://docs.scipy.org/doc/numpy/reference/routines.html
A backend implementation *may* expose subsets of the following
routine sections (as listed on previous link):
1) Array creation routines
2) Array manipulation routines
3) Binary operations
4) Discrete Fourier Transform
5) Functional programming
6) Input and Output
7) Linear Algebra
8) Logic functions
9) Mathematical functions
10) Random sampling
11) Set routines
12) Sorting searching and counting
13) Statistics
Currently unimplemented/unsupported features:
1) String Operations
2) C-Types Foreign Function Interface
3) Datetime Support Functions
4) Data type routines
5) Optionally Scipy-accelerated routines
6) Mathematical functions with automatic domain
7) Floating point error handling
8) NumPy-specific help functions
9) Financial functions
10) Indexing routines
11) Masked Array operations
12) Matrix library
13) Miscellaneous routines
14) Padding arrays
15) Polynomials
16) Test support
17) Window functions
By default, all exposed methods raise a NotImplementedError with an
explicit message through the _not_implemented_yet method.
"""
__registered_backends = {}
"""
Contains all registered backends.
keys = array handle type.
values = corresponding backend class.
Used to wrap array handles in _return().
"""
__DEBUG = False
"""
If set to true, prints all wrapped calls and arguments conversion.
"""
[docs]
@classmethod
def get_or_create(cls, **kwds):
cls._not_implemented_yet("get_or_create")
[docs]
@staticmethod
def get_alignment_and_size(shape, dtype, min_alignment=None):
"""
Returns number of bytes to allocate an array of given
shape and given dtype, aligned on given alignment.
Returned alignment will be at least dtype.itemsize.
Alignment should non zero and a power of two, or None
in which case it will be set to 1.
"""
bytes_per_elem = dtype.itemsize
min_alignment = min_alignment or 1
min_alloc_bytes = prod(shape) * bytes_per_elem
msg0 = "min_alignment is not a power of two, got {}."
msg1 = "bytes_per_elem is not a power of two, got {}."
assert min_alloc_bytes >= 1, "min_alloc_bytes <= 0."
assert min_alignment >= 1, "min_alignment <= 0."
assert (min_alignment & (min_alignment - 1)) == 0, msg0.format(min_alignment)
assert (bytes_per_elem & (bytes_per_elem - 1)) == 0, msg1.format(bytes_per_elem)
alignment = max(min_alignment, bytes_per_elem)
size = min_alloc_bytes
nbytes = min_alloc_bytes + alignment - 1
return (size, nbytes, alignment)
@staticmethod
def _register_backend(handle, backend_cls):
ArrayBackend.__registered_backends[handle] = backend_cls
@staticmethod
def _registered_backends():
return ArrayBackend.__registered_backends.copy()
@classmethod
def _not_implemented_yet(cls, funname):
msg = "{}::{}() has not been implemented yet."
msg = msg.format(cls.__name__, funname)
raise NotImplementedError(msg)
@classmethod
def _unsupported_argument(cls, fname, argname, arg, default_value=None):
if arg != default_value:
msg = "{}::{}() has been implemented but argument '{}' is not "
msg += "supported and should be set to {}."
msg = msg.format(cls.__name__, fname, argname, default_value)
raise NotImplementedError(msg)
@classmethod
def _check_argtype(cls, fname, argname, arg, argself):
if not isinstance(argself, tuple):
argself = (argself,)
if not arg.__class__ in argself:
msg = "{}::{}(): argument type mismatch, expected a {}"
msg += " for argument '{}' but got a {}."
msg = msg.format(cls.__name__, fname, argself, argname, arg.__class__)
raise TypeError(msg)
def __new__(cls, allocator, **kwds):
return super().__new__(cls, tag_prefix="bk", tagged_cls=ArrayBackend, **kwds)
def __init__(self, allocator, **kwds):
"""
Initialize an ArrayBackend with guven allocator.
"""
check_instance(allocator, AllocatorBase)
super().__init__(**kwds)
self._allocator = allocator
[docs]
@classmethod
def default_backend_from_kind(cls, *kinds):
from hysop.core.arrays.all import default_host_array_backend
for kind in kinds:
if kind == Backend.HOST:
return default_host_array_backend
msg = "Could not find any known default backend kind."
raise RuntimeError(msg)
[docs]
def any_backend_from_kind(self, *kinds):
for kind in kinds:
if kind == self.kind:
return self
return self.default_backend_from_kind(*kinds)
def __eq__(self, other):
if not other.__class__ is self.__class__:
return NotImplemented
eq = self._allocator is other._allocator
return eq
def __ne__(self, other):
if not other.__class__ is self.__class__:
return NotImplemented
ne = self._allocator is not other._allocator
return ne
def __hash__(self):
return id(self._allocator)
[docs]
@abstractmethod
def get_host_array_backend(self):
msg = f"get_host_array_backend() not implemented in {self.__class__}."
raise NotImplementedError(msg)
host_array_backend = property(get_host_array_backend)
[docs]
@abstractmethod
def short_description(self):
pass
[docs]
def get_allocator(self):
"""
Get the allocated associated to this backend.
"""
return self._allocator
@property
def max_alloc_size(self):
"""
Get the maximal size of allocatable contiguous chunk of memory in bytes.
"""
return self._allocator.max_alloc_size()
allocator = property(get_allocator)
def _prepare_args(self, *args, **kargs):
"""
Prepare all arguments for a call.
"""
if ArrayBackend.__DEBUG:
print("__prepare_args")
args = list(args)
for i, arg in enumerate(args):
args[i] = self._arg(arg)
for k, arg in kargs.items():
kargs[k] = self._arg(arg)
if "synchronize" in kargs:
msg = "synchronize cannot be an argument to pyopencl."
raise RuntimeError(msg)
return tuple(args), kargs
def _return(self, ret, **kargs):
"""
Wrap returned value(s) if they match a backend array.
"""
if isinstance(ret, tuple):
if ArrayBackend.__DEBUG:
print("__return", [r.__class__.__name__ for r in ret])
values = list(ret)
for i, val in enumerate(values):
if self.can_wrap(val):
values[i] = self.wrap(val, **kargs)
elif self.host_array_backend.can_wrap(val):
values[i] = self.host_array_backend.wrap(val)
return tuple(values)
if ArrayBackend.__DEBUG:
print("__return", ret.__class__.__name__)
if self.can_wrap(ret):
ret = self.wrap(ret, **kargs)
elif self.host_array_backend.can_wrap(ret):
ret = self.host_array_backend.wrap(ret)
return ret
def _call(self, functor, *varargs, **kwargs):
"""
Prepare arguments for a call to functor and calls it.
If returned value contains an array handle, it is wrapped into
the corresponding hysop.core.arrays.
"""
if ArrayBackend.__DEBUG:
print(f"__call {functor.__name__}")
args, kargs, _ret, ret = None, None, None, None
try:
args, kargs = self._prepare_args(*varargs, **kwargs)
_ret = functor(*args, **kargs)
ret = self._return(_ret)
except Exception as e:
def get_name(val):
if hasattr(val, "__class__"):
name = val.__class__.__name__
elif hasattr(val, "__name__"):
name = val.__name__
else:
name = val
if hasattr(val, "__class__") and val.__class__ in [
type,
int,
float,
np.dtype,
list,
tuple,
set,
]:
name += f" = {val}"
return name
def format(val):
if val is None:
return "Uninitialized"
if isinstance(val, tuple):
return ", ".join([get_name(v) for v in val])
elif isinstance(val, dict):
val = [f"{k} => {get_name(val[k])}" for k in sorted(val.keys())]
return "\n\t".join(val)
msg = """
Call of {} ({}) from class self={} failed
Before argument processing:
args: {}
kargs:
{}
returns: {}
After argument processing:
args: {}
kargs:
{}
returns: {}
Exception was:
{}
""".format(
functor,
functor.__name__,
self.__class__.__name__,
format(varargs),
format(kwargs),
format(_ret),
format(args),
format(kargs),
format(ret),
e,
)
print(msg)
raise
return ret
def _alloc_outputs(self, fname, kargs):
if ArrayBackend.__DEBUG:
print("__begin allocs")
shapes = []
orders = []
input_dtypes = {}
output_arg_names = []
for argname, arg in kargs.items():
if argname.find("out") >= 0:
if arg is None:
output_arg_names.append(argname)
elif self.can_wrap(arg):
arg = self.wrap(arg)
input_dtypes[argname] = arg.dtype
shapes.append(arg.shape)
orders.append(arg.order)
if not output_arg_names:
return
if not all(shape == shapes[0] for shape in shapes):
msg = f"Shape mismatch for array operands:\n {shapes}"
raise RuntimeError(msg)
else:
shape = shapes[0]
if not all(order == orders[0] for order in orders):
order = MemoryOrdering.C_CONTIGUOUS
else:
order = orders[0]
if "axis" in kargs:
# this is a reduction, we get rid of reduced axis
axis = kargs["axis"]
if axis is None:
shape = tuple()
else:
axis = to_tuple(axis)
_shape = []
for axe, s in enumerate(shape):
if axe not in axis:
_shape.append(s)
shape, _shape = to_tuple(_shape), shape
else:
axis = None
_shape = shape
if not shape:
# scalar output, do not allocate an array
return
output_dtypes = self._find_output_dtypes(fname, input_dtypes, output_arg_names)
if ArrayBackend.__DEBUG:
print(f"__allocating outputs for function {fname}")
print(f" *shape: {shape} (input shape={_shape}, axis={axis})")
print(f" *order: {order}")
print(f" *input dtypes: {input_dtypes}")
print(f" *deduced output dtypes: {output_dtypes}")
f = getattr(np, fname)
if isinstance(f, np.ufunc):
ftypes = f.types
ftypes_str = []
for ftype in ftypes:
type_info = {}
fin, fout = ftype.split("->")
for typechar in fin + fout:
try:
type_info[typechar] = np.typename(typechar)
except:
type_info[typechar] = "unknown type"
ss = "{}->{} ({})".format(
fin, fout, ", ".join(f"{k}={v}" for (k, v) in type_info.items())
)
ftypes_str.append(ss)
print(
" *ufunc available signatures:\n {}".format(
"\n ".join(ftypes_str)
)
)
for argname in output_arg_names:
dtype = output_dtypes[argname]
kargs[argname] = self.empty(shape=shape, dtype=dtype, order=order).handle
if ArrayBackend.__DEBUG:
print("__end allocs")
def _find_output_dtypes(self, fname, input_dtypes, output_arg_names):
output_dtypes = {}
dtypes = tuple(input_dtypes.values())
dtype = np.find_common_type([], dtypes)
if fname.find("frexp") == 0:
output_dtypes["out1"] = match_float_type(dtype)
output_dtypes["out2"] = np.int32
else:
# all outputs share the same dtype
if fname in [
"rint",
"floor",
"ceil",
"trunc",
"exp",
"exp2",
"expm1",
"log",
"log1p",
"log2",
"log10",
"logaddexp",
"logaddexp2",
"ldexp",
"sqrt",
"cbrt",
"hypot",
"fabs",
"copysign",
"modf",
"sin",
"cos",
"tan",
"arcsin",
"arccos",
"arctan",
"arctan2",
"sinh",
"cosh",
"tanh",
"arcsinh",
"arccosh",
"arctanh",
"rad2deg",
"deg2rad",
]:
if is_complex(dtype):
dtype = match_complex_type(dtype)
else:
dtype = match_float_type(dtype)
elif fname in ["absolute"]:
if is_complex(dtype):
dtype = complex_to_float_dtype(dtype)
elif fname in ["true_divide"]:
if dtypes[0] == dtypes[1]:
dtype0 = dtypes[0]
if is_fp(dtype0) or is_complex(dtype0):
dtype = dtype0
else:
dtype = np.float64
else:
dtype = np.float64
for argname in output_arg_names:
output_dtypes[argname] = dtype
return output_dtypes
############################
# BACKEND SPECIFIC METHODS #
[docs]
@abstractmethod
def wrap(self, handle, **kargs):
"""
Create a backend specific Array from the corresponding array handle.
"""
pass
[docs]
@abstractmethod
def can_wrap(self, handle, **kargs):
"""
Should return True if handle is an Array or a array handle corresponding
this backend.
"""
pass
def _arg(self, arg):
"""
Prepare one argument for a call (non backend specific argument conversion).
Can be extended for backend specific arguments.
"""
from hysop.core.arrays.array import Array
if isinstance(arg, Array):
return arg.handle
elif isinstance(arg, MemoryOrdering):
if arg == MemoryOrdering.C_CONTIGUOUS:
return "C"
elif arg == MemoryOrdering.F_CONTIGUOUS:
return "F"
elif arg == MemoryOrdering.SAME_ORDER:
return "K"
elif arg == MemoryOrdering.OUT_OF_ORDER:
msg = f"Unsupported memory ordering {arg}."
raise RuntimeError(msg)
else:
msg = f"Unknown memory ordering {arg}."
raise RuntimeError(msg)
else:
return arg
[docs]
def copyto(self, dst, src, **kargs):
"""
src is an Array
dst can be everything
"""
self._not_implemented_yet("copyto")
##############################
# EXTRA AND MODIFIED METHODS #
[docs]
def fill(self, a, value):
"""
Fill the array with given value
"""
self._not_implemented_yet("fill")
[docs]
def memcpy(self, dst, src, **kargs):
"""
Copy memory from src buffer to dst buffer .
"""
from hysop.core.arrays.array import Array
from hysop.core.arrays.all import HostArrayBackend
if isinstance(src, Array):
src.backend.copyto(dst, src, **kargs)
elif isinstance(dst, Array):
cls = src.__class__
if cls in ArrayBackend.__registered_backends:
backend_cls = ArrayBackend.__registered_backends[cls]
if isinstance(dst.backend, backend_cls):
src = dst.backend.wrap(src)
dst.backend.copyto(dst, src, **kargs)
elif backend_cls is HostArrayBackend:
host_array_backend = dst.backend.host_array_backend
src = host_array_backend.wrap(src)
host_array_backend.copyto(dst, src, **kargs)
else:
msg = "dst does not match registered backend for type {}."
msg = msg.format(cls)
raise TypeError(msg)
elif cls in [list, tuple, set] and isinstance(
dst.backend, HostArrayBackend
):
src = dst.backend.asarray(src)
dst.backend.copyto(dst, src, **kargs)
else:
print(src.__class__, dst.__class__)
msg = "src cannot be converted to type Array."
raise TypeError(msg)
else:
msg = "Neither src nor dst are of type Array."
raise TypeError(msg)
###########################
# ARRAY CREATION ROUTINES #
# See https://docs.scipy.org/doc/numpy/reference/routines.array-creation.html
# Ones and zeros
[docs]
def empty(self, shape, dtype=HYSOP_REAL, order=default_order):
"""
Return a new array of given shape and type, without initializing entries.
"""
self._not_implemented_yet("empty")
[docs]
def empty_like(
self, a, dtype=None, order=MemoryOrdering.SAME_ORDER, subok=True, shape=None
):
"""
Return a new array with the same shape and type as a given array.
"""
self._not_implemented_yet("empty_like")
[docs]
def eye(self, N, M, k, dtype=None):
"""
Return a 2-D array with ones on the diagonal and zeros elsewhere.
"""
self._not_implemented_yet("eye")
[docs]
def identity(self, n, dtype=None):
"""
Return the identity array.
"""
self._not_implemented_yet("identity")
[docs]
def ones(self, shape, dtype=None, order=default_order):
"""
Return a new array of given shape and type, filled with ones.
"""
self._not_implemented_yet("ones")
[docs]
def ones_like(
self, a, dtype=None, order=MemoryOrdering.SAME_ORDER, subok=True, shape=None
):
"""
Return an array of ones with the same shape and type as a given array.
"""
self._not_implemented_yet("ones_like")
[docs]
def zeros(self, shape, dtype=None, order=default_order):
"""
Return a new array of given shape and type, filled with zeros.
"""
self._not_implemented_yet("zeros")
[docs]
def zeros_like(
self, a, dtype=None, order=MemoryOrdering.SAME_ORDER, subok=True, shape=None
):
"""
Return an array of zeros with the same shape and type as a given array.
"""
self._not_implemented_yet("zeros_like")
[docs]
def full(self, shape, fill_value, dtype=None, order=default_order):
"""
Return a new array of given shape and type, filled with fill_value.
"""
self._not_implemented_yet("full")
[docs]
def full_like(
self,
a,
fill_value,
dtype=None,
order=MemoryOrdering.SAME_ORDER,
subok=True,
shape=None,
):
"""
Return a full array with the same shape and type as a given array.
"""
self._not_implemented_yet("full_like")
# From existing data
[docs]
def array(
self, object, dtype=None, copy=True, order=default_order, subok=False, ndmin=0
):
"""
Create an array.
"""
self._not_implemented_yet("array")
[docs]
def asarray(self, a, dtype=None, order=default_order, **kargs):
"""
Convert the input to an array.
"""
self._not_implemented_yet("asarray")
[docs]
def asanyarray(self, a, dtype=None, order=default_order):
"""
Convert the input to an ndarray, but pass ndarray subclasses through.
"""
self._not_implemented_yet("asanyarray")
[docs]
def asmatrix(self, data, dtype=None):
"""
Interpret the input as a matrix.
"""
self._not_implemented_yet("asmatrix")
[docs]
def copy(self, a, order=MemoryOrdering.SAME_ORDER):
"""
Return an array copy of the given object.
"""
self._not_implemented_yet("copy")
[docs]
def frombuffer(self, afer, dtype=HYSOP_REAL, count=-1, offset=0):
"""
Interpret a afer as a 1-dimensional array.
"""
self._not_implemented_yet("fromafer")
[docs]
def fromfile(self, file, dtype=HYSOP_REAL, count=-1, sep=""):
"""
Construct an array from data in a text or binary file.
"""
self._not_implemented_yet("fromfile")
[docs]
def fromfunction(self, function, shape, dtype=HYSOP_REAL):
"""
Construct an array by executing a function over each coordinate.
"""
self._not_implemented_yet("fromfunction")
[docs]
def fromiter(self, iterable, dtype=HYSOP_REAL, count=-1):
"""
Create a new 1-dimensional array from an iterable object.
"""
self._not_implemented_yet("fromiter")
# Numerical ranges
[docs]
def arange(self, dtype=HYSOP_INTEGER, *args, **kargs):
"""
Return evenly spaced values within a given interval.
"""
self._not_implemented_yet("arange")
[docs]
def linspace(
self, start, stop, num=50, endpoint=True, retstep=False, dtype=HYSOP_REAL
):
"""
Return evenly spaced numbers over a specified interval.
"""
self._not_implemented_yet("linspace")
[docs]
def logspace(self, start, stop, num=50, endpoint=True, base=10.0, dtype=HYSOP_REAL):
"""
Return numbers spaced evenly on a log scale.
"""
self._not_implemented_yet("logspace")
[docs]
def geomspace(self, start, stop, num=50, endpoint=True, dtype=HYSOP_REAL):
"""
Return numbers spaced evenly on a log scale (a geometric progression).
"""
self._not_implemented_yet("geomspace")
[docs]
def meshgrid(self, *xi, **kwargs):
"""
Return coordinate matrices from coordinate vectors.
"""
self._not_implemented_yet("meshgrid")
# Building matrices
[docs]
def diag(self, v, k=0):
"""
Extract a diagonal or construct a diagonal array.
"""
self._not_implemented_yet("diag")
[docs]
def diagflat(self, v, k=0):
"""
Create a two-dimensional array with the flattened input as a diagonal.
"""
self._not_implemented_yet("diagflat")
[docs]
def tri(self, N, M=None, k=0, dtype=HYSOP_REAL):
"""
An array with ones at and below the given diagonal and zeros elsewhere.
"""
self._not_implemented_yet("tri")
[docs]
def tril(self, m, k):
"""
Lower triangle of an array.
"""
self._not_implemented_yet("tril")
[docs]
def triu(self, m, k=0):
"""
Upper triangle of an array.
"""
self._not_implemented_yet("triu")
[docs]
def vander(self, x, N=None, increasing=False):
"""
Generate a Vandermonde matrix.
"""
self._not_implemented_yet("vander")
###############################
# ARRAY MANIPULATION ROUTINES #
# See https://docs.scipy.org/doc/numpy/reference/routines.array-manipulation.html
# Changing array shape
[docs]
def reshape(self, a, newshape, order=default_order):
"""
Gives a new shape to an array without changing its data.
"""
self._not_implemented_yet("reshape")
[docs]
def ravel(self, a, order=MemoryOrdering.SAME_ORDER):
"""
Return a contiguous flattened array.
"""
self._not_implemented_yet("ravel")
# Transpose-like operations
# /!\ those functions alter the logical transposition state /!\
[docs]
def moveaxis(self, a, source, destination):
"""
Move axes of an array to new positions.
Axe 0 is the slowest varying index, last axe is the fastest varying index.
"""
axes = tuple(i for i in range(a.ndim))
if source > destination:
axes = (
axes[:destination]
+ (source,)
+ axes[destination:source]
+ axes[source + 1 :]
)
else:
axes = (
axes[:source]
+ axes[source + 1 : destination]
+ (source,)
+ axes[destination:]
)
return self.transpose(a=a, axes=axes)
[docs]
def rollaxis(self, a, axis, start=0):
"""
Roll the specified axis backwards, until it lies in a given position.
Axe 0 is the slowest varying index, last axe is the fastest varying index.
"""
axes = tuple(np.roll(range(a.ndim), shift=-start).tolist())
return self.transpose(a=a, axes=axes)
[docs]
def swapaxes(self, a, axis1, axis2):
"""
Interchange two axes of an array.
Axe 0 is the slowest varying index, last axe is the fastest varying index.
"""
axes = list(range(a.ndim))
axes[axis1] = axis2
axes[axis2] = axis1
axes = tuple(axes)
return self.transpose(a=a, axes=axes)
[docs]
def transpose(self, a, axes=None):
"""
Permute the dimensions of an array.
Axe 0 is the slowest varying index, last axe is the fastest varying index.
Default permutation is (0,...,ndim-1).
"""
self._not_implemented_yet("transpose")
# Changing number of dimensions
[docs]
def atleast_1d(self, *arys):
"""
Convert inputs to arrays with at least one dimension.
"""
self._not_implemented_yet("atleast_1d")
[docs]
def atleast_2d(self, *arys):
"""
View inputs as arrays with at least two dimensions.
"""
self._not_implemented_yet("atleast_2d")
[docs]
def atleast_3d(self, *arys):
"""
View inputs as arrays with at least three dimensions.
"""
self._not_implemented_yet("atleast_3d")
[docs]
def broadcast_to(self, array, shape, subok=False):
"""
Broadcast an array to a new shape.
"""
self._not_implemented_yet("broadcast_to")
[docs]
def broadcast_arrays(self, *args, **kwargs):
"""
Broadcast any number of arrays against each other.
"""
self._not_implemented_yet("broadcast_arrays")
[docs]
def expand_dims(self, a, axis):
"""
Expand the shape of an array.
"""
self._not_implemented_yet("expand_dims")
[docs]
def squeeze(self, a, axis=None):
"""
Remove single-dimensional entries from the shape of an array.
"""
self._not_implemented_yet("squeeze")
# Changing kind of array
[docs]
def asfortranarray(self, a, dtype=None):
"""
Return an array laid out in Fortran order in memory.
"""
self._not_implemented_yet("asfortranarray")
[docs]
def ascontiguousarray(self, a, dtype=None):
"""
Return a contiguous array in memory (C order).
"""
self._not_implemented_yet("ascontiguousarray")
[docs]
def asarray_chkfinite(self, a, dtype=None, order=default_order):
"""
Convert the input to an array, checking for NaNs or Infs.
"""
self._not_implemented_yet("asarray_chkfinite")
[docs]
def asscalar(self, a):
"""
Convert an array of size 1 to its scalar equivalent.
"""
self._not_implemented_yet("asscalar")
[docs]
def require(self, a, dtype=None, requirements=None):
"""
Return an ndarray of the provided type that satisfies requirements.
"""
self._not_implemented_yet("require")
# Joining arrays
[docs]
def concatenate(self, a, axis=0):
"""
Join a sequence of arrays along an existing axis.
"""
self._not_implemented_yet("concatenate")
[docs]
def stack(self, arrays, axis=0):
"""
Join a sequence of arrays along a new axis.
"""
self._not_implemented_yet("stack")
[docs]
def column_stack(self, tup):
"""
Stack 1-D arrays as columns into a 2-D array.
"""
self._not_implemented_yet("column_stack")
[docs]
def dstack(self, tup):
"""
Stack arrays in sequence depth wise (along third axis).
"""
self._not_implemented_yet("dstack")
[docs]
def hstack(self, tup):
"""
Stack arrays in sequence horizontally (column wise).
"""
self._not_implemented_yet("hstack")
[docs]
def vstack(self, tup):
"""
Stack arrays in sequence vertically (row wise).
"""
self._not_implemented_yet("vstack")
# Splitting arrays
[docs]
def split(self, ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
"""
self._not_implemented_yet("split")
[docs]
def array_split(self, ary, indices_or_sections, axis=0):
"""
Split an array into multiple sub-arrays.
"""
self._not_implemented_yet("array_split")
[docs]
def dsplit(self, ary, indices_or_sections):
"""
Split array into multiple sub-arrays along the 3rd axis (depth).
"""
self._not_implemented_yet("dsplit")
[docs]
def hsplit(self, ary, indices_or_sections):
"""
Split an array into multiple sub-arrays horizontally (column-wise).
"""
self._not_implemented_yet("hsplit")
[docs]
def vsplit(self, ary, indices_or_sections):
"""
Split an array into multiple sub-arrays vertically (row-wise).
"""
self._not_implemented_yet("vsplit")
# Tiling arrays
[docs]
def tile(self, A, reps):
"""
Construct an array by repeating A the number of times given by reps.
"""
self._not_implemented_yet("tile")
[docs]
def repeat(self, a, repeats, axis=None):
"""
Repeat elements of an array.
"""
self._not_implemented_yet("repeat")
# Adding and removing elements
[docs]
def delete(self, arr, obj, axis=None):
"""
Return a new array with sub-arrays along an axis deleted.
"""
self._not_implemented_yet("delete")
[docs]
def insert(self, arr, obj, values, axis=None):
"""
Insert values along the given axis before the given indices.
"""
self._not_implemented_yet("insert")
[docs]
def append(self, arr, values, axis=None):
"""
Append values to the end of an array.
"""
self._not_implemented_yet("append")
[docs]
def resize(self, a, new_shape):
"""
Return a new array with the specified shape.
"""
self._not_implemented_yet("resize")
[docs]
def trim_zeros(self, filt, trim="fb"):
"""
Trim the leading and/or trailing zeros from a 1-D array or sequence.
"""
self._not_implemented_yet("trim_zeros")
# Rearranging elements
[docs]
def flip(self, m, axis):
"""
Reverse the order of elements in an array along the given axis.
"""
self._not_implemented_yet("flip")
[docs]
def fliplr(self, m):
"""
Flip array in the left/right direction.
"""
self._not_implemented_yet("fliplr")
[docs]
def flipud(self, m):
"""
Flip array in the up/down direction.
"""
self._not_implemented_yet("flipud")
[docs]
def roll(self, a, shift, axis=None):
"""
Roll array elements along a given axis.
"""
self._not_implemented_yet("roll")
[docs]
def rot90(self, m, k=1, axes=(0, 1)):
"""
Rotate an array by 90 degrees in the plane specified by axes.
"""
self._not_implemented_yet("rot90")
#####################
# BINARY OPERATIONS #
# See https://docs.scipy.org/doc/numpy/reference/routines.bitwise.html
# Elementwise bit operations
[docs]
def bitwise_and(self, x1, x2, out=None):
"""
Compute the bit-wise AND of two arrays element-wise.
"""
self._not_implemented_yet("bitwise_and")
[docs]
def bitwise_or(self, x1, x2, out=None):
"""
Compute the bit-wise OR of two arrays element-wise.
"""
self._not_implemented_yet("bitwise_or")
[docs]
def bitwise_xor(self, x1, x2, out=None):
"""
Compute the bit-wise XOR of two arrays element-wise.
"""
self._not_implemented_yet("bitwise_xor")
[docs]
def invert(self, x, out=None):
"""
Compute bit-wise inversion, or bit-wise NOT, element-wise.
"""
self._not_implemented_yet("invert")
[docs]
def left_shift(self, x1, x2, out=None):
"""
Shift the bits of an integer to the left.
"""
self._not_implemented_yet("left_shift")
[docs]
def right_shift(self, x1, x2, out=None):
"""
Shift the bits of an integer to the right.
"""
self._not_implemented_yet("right_shift")
# Bit packing
[docs]
def packbits(self, myarray, axis=None):
"""
Packs the elements of a binary-valued array into bits in a uint8 array.
"""
self._not_implemented_yet("packbits")
[docs]
def unpackbits(self, myarray, axis=None):
"""
Unpacks elements of a uint8 array into a binary-valued output array.
"""
self._not_implemented_yet("unpackbits")
##############################
# DISCRETE FOURIER TRANSFORM #
# See https://docs.scipy.org/doc/numpy/reference/routines.fft.html
# Standard FFTs
[docs]
def fft(self, a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional discrete Fourier Transform.
"""
self._not_implemented_yet("fft")
[docs]
def ifft(self, a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional inverse discrete Fourier Transform.
"""
self._not_implemented_yet("ifft")
[docs]
def fft2(self, a, s=None, axes=None, norm=None):
"""
Compute the 2-dimensional discrete Fourier Transform
"""
self._not_implemented_yet("fft2")
[docs]
def ifft2(self, a, s=None, axes=None, norm=None):
"""
Compute the 2-dimensional inverse discrete Fourier Transform.
"""
self._not_implemented_yet("ifft2")
[docs]
def fftn(self, a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional discrete Fourier Transform.
"""
self._not_implemented_yet("fftn")
[docs]
def ifftn(self, a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional inverse discrete Fourier Transform.
"""
self._not_implemented_yet("ifftn")
# Real FFTs
[docs]
def rfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the one-dimensional discrete Fourier Transform for real input.
"""
self._not_implemented_yet("rfft")
[docs]
def irfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the inverse of the n-point DFT for real input.
"""
self._not_implemented_yet("irfft")
[docs]
def rfft2(self, a, s=None, axes=(-2, -1), norm=None):
"""
Compute the 2-dimensional FFT of a real array.
"""
self._not_implemented_yet("rfft2")
[docs]
def irfft2(self, a, s=None, axes=(-2, -1), norm=None):
"""
Compute the 2-dimensional inverse FFT of a real array.
"""
self._not_implemented_yet("irfft2")
[docs]
def rfftn(self, a, s=None, axes=None, norm=None):
"""
Compute the N-dimensional discrete Fourier Transform for real input.
"""
self._not_implemented_yet("rfftn")
[docs]
def irfftn(self, a, s=None, axes=None, norm=None):
"""
Compute the inverse of the N-dimensional FFT of real input.
"""
self._not_implemented_yet("irfftn")
# Hermitian FFTs
[docs]
def hfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the FFT of a signal that has Hermitian symmetry, i.e., a real spectrum.
"""
self._not_implemented_yet("hfft")
[docs]
def ihfft(self, a, n=None, axis=-1, norm=None):
"""
Compute the inverse FFT of a signal that has Hermitian symmetry.
"""
self._not_implemented_yet("ihfft")
# Helper routines
[docs]
def fftfreq(self, n=None, d=1.0):
"""
Return the Discrete Fourier Transform sample frequencies.
"""
self._not_implemented_yet("fftfreq")
[docs]
def rfftfreq(self, n=None, d=1.0):
"""
Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft).
"""
self._not_implemented_yet("rfftfreq")
[docs]
def fftshift(self, x, axes=None):
"""
Shift the zero-frequency component to the center of the spectrum.
"""
self._not_implemented_yet("fftshift")
[docs]
def ifftshift(self, x, axes=None):
"""
The inverse of fftshift.
"""
self._not_implemented_yet("ifftshift")
##########################
# FUNCTIONAL PROGRAMMING #
# See https://docs.scipy.org/doc/numpy/reference/routines.functional.html
[docs]
def apply_along_axis(self, func1d, axis, arr, *args, **kwargs):
"""
Apply a function to 1-D slices along the given axis.
"""
self._not_implemented_yet("apply_along_axis")
[docs]
def apply_over_axes(self, func, a, axes):
"""
Apply a function repeatedly over multiple axes.
"""
self._not_implemented_yet("apply_over_axes")
[docs]
def vectorize(
self, pyfunc, otypes=None, doc=None, excluded=None, cache=False, signature=None
):
"""
Generalized function class.
"""
self._not_implemented_yet("vectorize")
[docs]
def frompyfunc(self, func, nin, nout):
"""
Takes an arbitrary Python function and returns a NumPy ufunc.
"""
self._not_implemented_yet("frompyfunc")
[docs]
def piecewise(self, x, condlist, funclist, *args, **kw):
"""
Evaluate a piecewise-defined function.
"""
self._not_implemented_yet("piecewise")
####################
# INPUT AND OUTPUT #
# See https://docs.scipy.org/doc/numpy/reference/routines.io.html
# NumPy binary files (NPY, NPZ)
[docs]
def load(
self, mmap_mode=None, allow_pickle=True, fix_imports=True, encoding="ASCII"
):
"""
Load arrays or pickled objects from .npy, .npz or pickled files.
"""
self._not_implemented_yet("load")
[docs]
def save(self, arr, file, allow_pickle=True, fix_imports=True):
"""
Save an array to a binary file in NumPy .npy format.
"""
self._not_implemented_yet("save")
[docs]
def savez(self, file, *args, **kwds):
"""
Save several arrays into a single file in uncompressed .npz format.
"""
self._not_implemented_yet("savez")
[docs]
def savez_compressed(self, file, *args, **kwds):
"""
Save several arrays into a single file in compressed .npz format.
"""
self._not_implemented_yet("savez_compressed")
# Text files
[docs]
def loadtxt(
self,
dtype=HYSOP_REAL,
comments="#",
delimiter=None,
converters=None,
skiprows=0,
usecols=None,
unpack=False,
ndmin=0,
):
"""
Load data from a text file.
"""
self._not_implemented_yet("loadtxt")
[docs]
def savetxt(
self,
fname,
X,
fmt="%.18e",
delimiter=" ",
newline="\n",
header="",
footer="",
comments="# ",
):
"""
Save an array to a text file.
"""
self._not_implemented_yet("savetxt")
[docs]
def genfromtxt(
self,
fname,
dtype=HYSOP_REAL,
comments="#",
delimiter=None,
skip_header=0,
skip_footer=0,
converters=None,
missing_values=None,
filling_values=None,
usecols=None,
names=None,
excludelist=None,
deletechars=None,
replace_space="_",
autostrip=False,
case_sensitive=True,
defaultfmt="f%i",
unpack=None,
usemask=False,
loose=True,
invalid_raise=True,
max_rows=None,
):
"""
Load data from a text file, with missing values handled as specified.
"""
self._not_implemented_yet("genfromtxt")
[docs]
def fromregex(self, file, regexp, dtype):
"""
Construct an array from a text file, using regular expression parsing.
"""
self._not_implemented_yet("fromregex")
[docs]
def fromstring(self, string, dtype=HYSOP_REAL, count=-1, sep=""):
"""
A new 1-D array initialized from raw binary or text data in a string.
"""
self._not_implemented_yet("fromstring")
# String formatting
[docs]
def array2string(
self,
a,
max_line_width=None,
precision=None,
suppress_small=None,
separator=" ",
prefix="",
style=repr,
formatter=None,
):
"""
Return a string representation of an array.
"""
self._not_implemented_yet("array2string")
[docs]
def array_repr(self, arr, max_line_width=None, precision=None, supress_small=None):
"""
Return the string representation of an array.
"""
self._not_implemented_yet("array_repr")
[docs]
def array_str(self, a, max_line_width=None, precision=None, suppress_small=None):
"""
Return a string representation of the data in an array.
"""
self._not_implemented_yet("array_str")
# Text formatting options
[docs]
def set_printoptions(
self,
precision=None,
threshold=None,
edgeitems=None,
linewidth=None,
suppress=None,
nanstr=None,
infstr=None,
formatter=None,
):
"""
Set printing options.
"""
self._not_implemented_yet("set_printoptions")
[docs]
def get_printoptions(self):
"""
Return the current print options.
"""
self._not_implemented_yet("get_printoptions")
[docs]
def set_string_function(self, f, repr=True):
"""
Set a Python function to be used when pretty printing arrays.
"""
self._not_implemented_yet("set_string_function")
# Base-n representations
[docs]
def binary_repr(self, num, width=None):
"""
Return the binary representation of the input number as a string.
"""
self._not_implemented_yet("binary_repr")
[docs]
def base_repr(self, number, base=2, padding=0):
"""
Return a string representation of a number in the given base system.
"""
self._not_implemented_yet("base_repr")
######################
### LINEAR ALGEBRA ###
# See https://docs.scipy.org/doc/numpy/reference/routines.linalg.html
# Matrix and vector products
[docs]
def dot(self, a, b, out=None):
"""
Dot product of two arrays.
"""
self._not_implemented_yet("dot")
[docs]
def vdot(self, a, b):
"""
Return the dot product of two vectors.
"""
self._not_implemented_yet("vdot")
[docs]
def inner(self, a, b):
"""
Inner product of two arrays.
"""
self._not_implemented_yet("inner")
[docs]
def outer(self, a, b, out=None):
"""
Compute the outer product of two vectors.
"""
self._not_implemented_yet("outer")
[docs]
def matmul(self, a, b, out=None):
"""
Matrix product of two arrays.
"""
self._not_implemented_yet("matmul")
[docs]
def tensordot(self, a, b, axes=2):
"""
Compute tensor dot product along specified axes for arrays >= 1-D.
"""
self._not_implemented_yet("tensordot")
[docs]
def einsum(
self,
subscripts,
out=None,
dtype=None,
order=MemoryOrdering.SAME_ORDER,
casting="safe",
optimize=False,
*operands,
):
"""
Evaluates the Einstein summation convention on the operands.
"""
self._not_implemented_yet("einsum")
[docs]
def matrix_power(self, M, n):
"""
Raise a square matrix to the integer power n.
"""
self._not_implemented_yet("matrix_power")
[docs]
def kron(self, a, b):
"""
Kronecker product of two arrays.
"""
self._not_implemented_yet("kron")
# Decompositions
[docs]
def cholesky(self, a):
"""
Cholesky decomposition.
"""
self._not_implemented_yet("cholesky")
[docs]
def qr(self, a, mode="reduced"):
"""
Compute the qr factorization of a matrix.
"""
self._not_implemented_yet("qr")
[docs]
def svd(self, a, full_matrices=True, compute_uv=True):
"""
Singular Value Decomposition.
"""
self._not_implemented_yet("svd")
# Matrix eigenvalues
[docs]
def eig(self, a):
"""
Compute the eigenvalues and right eigenvectors of a square array.
"""
self._not_implemented_yet("eig")
[docs]
def eigh(self, a, UPLO="L"):
"""
Return the eigenvalues and eigenvectors of a Hermitian or symmetric matrix.
"""
self._not_implemented_yet("eigh")
[docs]
def eigvals(self, a):
"""
Compute the eigenvalues of a general matrix.
"""
self._not_implemented_yet("eigvals")
[docs]
def eigvalsh(self, a, UPLO="L"):
"""
Compute the eigenvalues of a Hermitian or real symmetric matrix.
"""
self._not_implemented_yet("eigvalsh")
# Norms and other numbers
[docs]
def norm(self, x, ord=None, axis=None, keepdims=False):
"""
Matrix or vector norm.
"""
self._not_implemented_yet("norm")
[docs]
def cond(self, x, p=None):
"""
Compute the condition number of a matrix.
"""
self._not_implemented_yet("cond")
[docs]
def det(self, a):
"""
Compute the determinant of an array.
"""
self._not_implemented_yet("det")
[docs]
def matrix_rank(self, M, tol=None):
"""
Return matrix rank of array using SVD method
"""
self._not_implemented_yet("matrix_rank")
[docs]
def slogdet(self, a):
"""
Compute the sign and natural logarithm of the determinant of an array.
"""
self._not_implemented_yet("slogdet")
[docs]
def trace(self, a, offset=0, axis1=0, axis2=1, dtype=None, out=None):
"""
Return the sum along diagonals of the array.
"""
self._not_implemented_yet("trace")
# Solving equations and inverting matrices
[docs]
def solve(self, a, b):
"""
Solve a linear matrix equation, or system of linear scalar equations.
"""
self._not_implemented_yet("solve")
[docs]
def tensorsolve(self, a, b, axes=None):
"""
Solve the tensor equation a x = b for x.
"""
self._not_implemented_yet("tensorsolve")
[docs]
def lstsq(self, a, b, rcond=-1):
"""
Return the least-squares solution to a linear matrix equation.
"""
self._not_implemented_yet("lstsq")
[docs]
def inv(self, a):
"""
Compute the (multiplicative) inverse of a matrix.
"""
self._not_implemented_yet("inv")
[docs]
def pinv(self, a, rcond=1e-15):
"""
Compute the (Moore-Penrose) pseudo-inverse of a matrix.
"""
self._not_implemented_yet("pinv")
[docs]
def tensorinv(self, a, ind=2):
"""
Compute the 'inverse' of an N-dimensional array.
"""
self._not_implemented_yet("tensorinv")
###################
# LOGIC FUNCTIONS #
# See https://docs.scipy.org/doc/numpy/reference/routines.logic.html
# Truth value testing
[docs]
def any(self, a, axis=None, out=None):
"""
Test whether any array elements along a given axis evaluate to True.
"""
self._not_implemented_yet("any")
[docs]
def all(self, a, axis=None, out=None):
"""
Test whether all array elements along a given axis evaluate to True.
"""
self._not_implemented_yet("all")
# Array contents
[docs]
def isfinite(self, x, out=None):
"""
Test element-wise for finiteness (not infinity or not Not a Number).
"""
self._not_implemented_yet("isfinite")
[docs]
def isinf(self, x, out=None):
"""
Test element-wise for positive or negative infinity.
"""
self._not_implemented_yet("isinf")
[docs]
def isnan(self, x, out=None):
"""
Test element-wise for NaN and return result as a boolean array.
"""
self._not_implemented_yet("isnan")
[docs]
def isneginf(self, x, out=None):
"""
Test element-wise for negative infinity, return result as bool array.
"""
self._not_implemented_yet("isneginf")
[docs]
def isposinf(self, x, out=None):
"""
Test element-wise for positive infinity, return result as bool array.
"""
self._not_implemented_yet("isposinf")
# Logical operations
[docs]
def logical_and(self, x1, x2, out=None):
"""
Compute the truth value of x1 AND x2 element-wise.
"""
self._not_implemented_yet("logical_and")
[docs]
def logical_or(self, x1, x2, out=None):
"""
Compute the truth value of x1 OR x2 element-wise.
"""
self._not_implemented_yet("logical_or")
[docs]
def logical_not(self, x, out=None):
"""
Compute the truth value of NOT x element-wise.
"""
self._not_implemented_yet("logical_not")
[docs]
def logical_xor(self, x1, x2, out=None):
"""
Compute the truth value of x1 XOR x2, element-wise.
"""
self._not_implemented_yet("logical_xor")
# Comparisson
[docs]
def allclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
"""
Returns True if two arrays are element-wise equal within a tolerance.
"""
self._not_implemented_yet("allclose")
[docs]
def isclose(self, a, b, rtol=1e-05, atol=1e-08, equal_nan=False):
"""
Returns a boolean array where two arrays are element-wise equal within a tolerance.
"""
self._not_implemented_yet("isclose")
[docs]
def array_equal(self, a1, a2):
"""
True if two arrays have the same shape and elements, False otherwise.
"""
self._not_implemented_yet("array_equal")
[docs]
def array_equiv(self, a1, a2):
"""
returns True if input arrays are shape consistent and all elements equal.
"""
self._not_implemented_yet("array_equiv")
[docs]
def greater(self, x1, x2, out=None):
"""
Return the truth value of (x1 > x2) element-wise.
"""
self._not_implemented_yet("greater")
[docs]
def greater_equal(self, x1, x2, out=None):
"""
Return the truth value of (x1 >= x2) element-wise.
"""
self._not_implemented_yet("greater_equal")
[docs]
def less(self, x1, x2, out):
"""
Return the truth value of (x1 < x2) element-wise.
"""
self._not_implemented_yet("less")
[docs]
def less_equal(self, x1, x2, out):
"""
Return the truth value of (x1 =< x2) element-wise.
"""
self._not_implemented_yet("less_equal")
[docs]
def equal(self, x1, x2, out=None):
"""
Return (x1 == x2) element-wise.
"""
self._not_implemented_yet("equal")
[docs]
def not_equal(self, x1, x2, out=None):
"""
Return (x1 != x2) element-wise.
"""
self._not_implemented_yet("not_equal")
##########################
# MATHEMATICAL FUNCTIONS #
# See https://docs.scipy.org/doc/numpy/reference/routines.math.html
# Trigonometric functions
[docs]
def sin(self, x, out=None):
"""
Trigonometric sine, element-wise.
"""
self._not_implemented_yet("sin")
[docs]
def cos(self, x, out=None):
"""
Cosine element-wise.
"""
self._not_implemented_yet("cos")
[docs]
def tan(self, x, out=None):
"""
Compute tangent element-wise.
"""
self._not_implemented_yet("tan")
[docs]
def arcsin(self, x, out=None):
"""
Inverse sine, element-wise.
"""
self._not_implemented_yet("arcsin")
[docs]
def arccos(self, x, out=None):
"""
Trigonometric inverse cosine, element-wise.
"""
self._not_implemented_yet("arccos")
[docs]
def arctan(self, x, out=None):
"""
Trigonometric inverse tangent, element-wise.
"""
self._not_implemented_yet("arctan")
[docs]
def arctan2(self, x1, x2, out=None):
"""
Element-wise arc tangent of x1/x2 choosing the quadrant correctly.
"""
self._not_implemented_yet("arctan2")
[docs]
def hypot(self, x1, x2, out=None):
"""
Given the legs of a right triangle, return its hypotenuse.
"""
self._not_implemented_yet("hypot")
[docs]
def unwrap(self, p, discont=3.141592653589793, axis=-1):
"""
Unwrap by changing deltas between values to 2*pi complement.
"""
self._not_implemented_yet("unwrap")
[docs]
def deg2rad(self, x, out=None):
"""
Convert angles from degrees to radians.
"""
self._not_implemented_yet("deg2rad")
[docs]
def rad2deg(self, x, out=None):
"""
Convert angles from radians to degrees.
"""
self._not_implemented_yet("rad2deg")
# Hyperbolic functions
[docs]
def sinh(self, x, out=None):
"""
Hyperbolic sine, element-wise.
"""
self._not_implemented_yet("sinh")
[docs]
def cosh(self, x, out=None):
"""
Hyperbolic cosine, element-wise.
"""
self._not_implemented_yet("cosh")
[docs]
def tanh(self, x, out=None):
"""
Compute hyperbolic tangent element-wise.
"""
self._not_implemented_yet("tanh")
[docs]
def arcsinh(self, x, out=None):
"""
Inverse hyperbolic sine element-wise.
"""
self._not_implemented_yet("arcsinh")
[docs]
def arccosh(self, x, out=None):
"""
Inverse hyperbolic cosine, element-wise.
"""
self._not_implemented_yet("arccosh")
[docs]
def arctanh(self, x, out=None):
"""
Inverse hyperbolic tangent element-wise.
"""
self._not_implemented_yet("arctanh")
# Rounding
[docs]
def around(self, a, decimals=0, out=None):
"""
Evenly round to the given number of decimals, returns HYSOP_INTEGER.
"""
self._not_implemented_yet("around")
[docs]
def fix(self, x, y=None):
"""
Round to nearest integer towards zero.
"""
self._not_implemented_yet("fix")
[docs]
def rint(self, x, out=None):
"""
Round elements of the array to the nearest integer.
"""
self._not_implemented_yet("rint")
[docs]
def floor(self, x, out=None):
"""
Return the floor of the input, element-wise.
"""
self._not_implemented_yet("floor")
[docs]
def ceil(self, x, out=None):
"""
Return the ceiling of the input, element-wise.
"""
self._not_implemented_yet("ceil")
[docs]
def trunc(self, x, out=None):
"""
Return the truncated value of the input, element-wise.
"""
self._not_implemented_yet("trunc")
# Sums, product, differences
[docs]
def prod(self, a, axis=None, dtype=None, out=None):
"""
Return the product of array elements over a given axis.
"""
self._not_implemented_yet("prod")
[docs]
def sum(self, a, axis=None, dtype=None, out=None):
"""
Sum of array elements over a given axis.
"""
self._not_implemented_yet("sum")
[docs]
def nanprod(self, a, axis=None, dtype=None, out=None):
"""
Return the product of array elements over a given axis treating
Not a Numbers (NaNs) as ones.
"""
self._not_implemented_yet("nanprod")
[docs]
def nansum(self, a, axis=None, dtype=None, out=None):
"""
Return the sum of array elements over a given axis treating Not a Numbers (NaNs) as zero.
"""
self._not_implemented_yet("nansum")
[docs]
def cumprod(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative product of elements along a given axis.
"""
self._not_implemented_yet("cumprod")
[docs]
def cumsum(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative sum of the elements along a given axis.
"""
self._not_implemented_yet("cumsum")
[docs]
def nancumprod(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative product of array elements over a given axis treating
Not a Numbers (NaNs) as one.
"""
self._not_implemented_yet("nancumprod")
[docs]
def nancumsum(self, a, axis=None, dtype=None, out=None):
"""
Return the cumulative sum of array elements over a given axis treating
Not a Numbers (NaNs) as zero.
"""
self._not_implemented_yet("nancumsum")
[docs]
def diff(self, a, n=1, axis=-1):
"""
Calculate the n-th discrete difference along given axis.
"""
self._not_implemented_yet("diff")
[docs]
def ediff1d(self, ary, to_end=None, to_begin=None):
"""
The differences between consecutive elements of an array.
"""
self._not_implemented_yet("ediff1d")
[docs]
def gradient(self, f, *varargs, **kwargs):
"""
Return the gradient of an N-dimensional array.
"""
self._not_implemented_yet("gradient")
[docs]
def cross(self, a, b, axisa=-1, axisb=-1, axisc=-1, axis=None):
"""
Return the cross product of two (arrays of) vectors.
"""
self._not_implemented_yet("cross")
[docs]
def trapz(self, y, x=None, dx=1.0, axis=-1):
"""
Integrate along the given axis using the composite trapezoidal rule.
"""
self._not_implemented_yet("trapz")
# Exponents and logarithms
[docs]
def exp(self, x, out=None):
"""
Calculate the exponential of all elements in the input array.
"""
self._not_implemented_yet("exp")
[docs]
def exp2(self, x, out=None):
"""
Calculate 2**p for all p in the input array.
"""
self._not_implemented_yet("exp2")
[docs]
def expm1(self, x, out=None):
"""
Calculate exp(x) - 1 for all elements in the array.
"""
self._not_implemented_yet("expm1")
[docs]
def log(self, x, out=None):
"""
Natural logarithm, element-wise.
"""
self._not_implemented_yet("log")
[docs]
def log2(self, x, out=None):
"""
Base-2 logarithm of x.
"""
self._not_implemented_yet("log2")
[docs]
def log10(self, x, out=None):
"""
Return the base 10 logarithm of the input array, element-wise.
"""
self._not_implemented_yet("log10")
[docs]
def log1p(self, x, out=None):
"""
Return the natural logarithm of one plus the input array, element-wise.
"""
self._not_implemented_yet("log1p")
[docs]
def logaddexp(self, x1, x2, out=None):
"""
Logarithm of the sum of exponentiations of the inputs.
"""
self._not_implemented_yet("logaddexp")
[docs]
def logaddexp2(self, x1, x2, out=None):
"""
Logarithm of the sum of exponentiations of the inputs in base-2.
"""
self._not_implemented_yet("logaddexp2")
# Other special functions
[docs]
def i0(self, x):
"""
Modified Bessel function of the first kind, order 0.
"""
self._not_implemented_yet("i0")
[docs]
def sinc(self, x):
"""
Return the sinc function.
"""
self._not_implemented_yet("sinc")
# Floating point routines
[docs]
def signbit(self, x, out=None):
"""
Returns element-wise True where signbit is set (less than zero).
"""
self._not_implemented_yet("signbit")
[docs]
def copysign(self, x1, x2, out=None):
"""
Change the sign of x1 to that of x2, element-wise.
"""
self._not_implemented_yet("copysign")
[docs]
def frexp(self, x, out1=None, out2=None):
"""
Decompose the elements of x into mantissa and twos exponent.
"""
self._not_implemented_yet("frexp")
[docs]
def ldexp(self, x1, x2, out=None):
"""
Returns x1 * 2**x2, element-wise.
"""
self._not_implemented_yet("ldexp")
# Arithmetic operations
[docs]
def add(self, x1, x2, out=None):
"""
Add arguments element-wise.
"""
self._not_implemented_yet("add")
[docs]
def reciprocal(self, x, out=None):
"""
Return the reciprocal of the argument, element-wise.
"""
self._not_implemented_yet("reciprocal")
[docs]
def negative(self, x, out=None):
"""
Numerical negative, element-wise.
"""
self._not_implemented_yet("negative")
[docs]
def multiply(self, x1, x2, out=None):
"""
Multiply arguments element-wise.
"""
self._not_implemented_yet("multiply")
[docs]
def divide(self, x1, x2, out=None):
"""
Divide arguments element-wise.
"""
self._not_implemented_yet("divide")
[docs]
def power(self, x1, x2, out=None):
"""
First array elements raised to powers from second array, element-wise.
"""
self._not_implemented_yet("power")
[docs]
def subtract(self, x1, x2, out=None):
"""
Subtract arguments, element-wise.
"""
self._not_implemented_yet("subtract")
[docs]
def true_divide(self, x1, x2, out=None):
"""
Returns a true division of the inputs, element-wise.
"""
self._not_implemented_yet("true_divide")
[docs]
def floor_divide(self, x1, x2, out=None):
"""
Return the largest integer smaller or equal to the division of the inputs.
"""
self._not_implemented_yet("floor_divide")
[docs]
def fmod(self, x1, x2, out=None):
"""
Return the element-wise remainder of division (REM).
Remainder has the same sign as the divisor x2.
This should not be confused with the Python modulus operator x1 % x2.
"""
self._not_implemented_yet("fmod")
[docs]
def mod(self, x1, x2, out=None):
"""
Return element-wise remainder of division (MOD).
Remainder has the same sign as the divident x1.
It is complementary to the function floor_divide and
match Python modfulus operator x1 % x2.
"""
self._not_implemented_yet("mod")
[docs]
def modf(self, x, out1=None, out2=None):
"""
Return the fractional and integral parts of an array, element-wise.
"""
self._not_implemented_yet("modf")
# Handling complex numbers
[docs]
def angle(self, z, deg=False):
"""
Return the angle of the complex argument.
"""
self._not_implemented_yet("angle")
[docs]
def real(self, val):
"""
Return the real part of the elements of the array.
"""
self._not_implemented_yet("real")
[docs]
def imag(self, val):
"""
Return the imaginary part of the elements of the array.
"""
self._not_implemented_yet("imag")
[docs]
def conj(self, x, out=None):
"""
Return the complex conjugate, element-wise.
"""
self._not_implemented_yet("conj")
# Miscellanous
[docs]
def convolve(self, a, v, mode="full"):
"""
Returns the discrete, linear convolution of two one-dimensional sequences.
"""
self._not_implemented_yet("convolve")
[docs]
def clip(self, a, a_min, a_max, out=None):
"""
Clip (limit) the values in an array.
"""
self._not_implemented_yet("clip")
[docs]
def sqrt(self, x, out=None):
"""
Return the positive square-root of an array, element-wise.
"""
self._not_implemented_yet("sqrt")
[docs]
def cbrt(self, x, out=None):
"""
Return the cube-root of an array, element-wise.
"""
self._not_implemented_yet("cbrt")
[docs]
def square(self, x, out=None):
"""
Return the element-wise square of the input.
"""
self._not_implemented_yet("square")
[docs]
def nan_to_num(self, x):
"""
Replace nan with zero and inf with finite numbers.
"""
self._not_implemented_yet("nan_to_num")
[docs]
def real_if_close(self, a, tol=100):
"""
If complex input returns a real array if complex parts are close to zero.
"""
self._not_implemented_yet("real_if_close")
[docs]
def interp(self, x, xp, fp, left=None, right=None, period=None):
"""
One-dimensional linear interpolation.
"""
self._not_implemented_yet("interp")
[docs]
def maximum(self, x1, x2, out=None):
"""
Element-wise maximum of array elements.
"""
self._not_implemented_yet("maximum")
[docs]
def minimum(self, x1, x2, out=None):
"""
Element-wise minimum of array elements.
"""
self._not_implemented_yet("minimum")
[docs]
def fmin(self, x1, x2, out=None):
"""
Element-wise maximum of array elements, ignore NaNs.
"""
self._not_implemented_yet("fmin")
[docs]
def fmax(self, x1, x2, out=None):
"""
Element-wise minimum of array elements, ignore NaNs.
"""
self._not_implemented_yet("fmax")
[docs]
def fabs(self, x, out=None):
"""
Calculate the absolute value element-wise, outputs HYSOP_REAL unless out is set.
"""
self._not_implemented_yet("fabs")
[docs]
def absolute(self, x, out=None):
"""
Calculate the absolute value element-wise.
"""
self._not_implemented_yet("absolute")
[docs]
def sign(self, x, out=None):
"""
Returns an element-wise indication of the sign of a number.
"""
self._not_implemented_yet("sign")
###################
# RANDOM SAMPLING #
# See https://docs.scipy.org/doc/numpy/reference/routines.random.html
# Simple random data
[docs]
def rand(self, shape, **kwds):
"""
Random values in a given shape between 0.0 and 1.0.
"""
self._not_implemented_yet("rand")
[docs]
def randn(self, shape, **kwds):
"""
Return a sample (or samples) from the 'standard normal' distribution.
"""
self._not_implemented_yet("randn")
[docs]
def randint(self, low, high=None, size=None, dtype=HYSOP_INTEGER):
"""
Return random integers from low (inclusive) to high (exclusive).
"""
self._not_implemented_yet("randint")
[docs]
def random_integers(self, low, high=None, size=None):
"""
Random integers of type np.int between low and high, inclusive.
"""
self._not_implemented_yet("random_integers")
[docs]
def random_sample(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
self._not_implemented_yet("random_sample")
[docs]
def random(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
self._not_implemented_yet("random")
[docs]
def ranf(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
self._not_implemented_yet("ranf")
[docs]
def sample(self, size=None):
"""
Return random floats in the half-open interval 0.0, 1.0).
"""
self._not_implemented_yet("sample")
[docs]
def choice(self, a, size=None, replace=True, p=None):
"""
Generates a random sample from a given 1-D array
"""
self._not_implemented_yet("choice")
[docs]
def bytes(self, length):
"""
Return random bytes.
"""
self._not_implemented_yet("bytes")
# Permutations
[docs]
def shuffle(self, x):
"""
Modify a sequence in-place by shuffling its contents.
"""
self._not_implemented_yet("shuffle")
[docs]
def permutation(self, x):
"""
Randomly permute a sequence, or return a permuted range.
"""
self._not_implemented_yet("permutation")
# Distributions
[docs]
def beta(self, a, b, size=None):
"""
Draw samples from a Beta distribution.
"""
self._not_implemented_yet("beta")
[docs]
def binomial(self, n, p, size=None):
"""
Draw samples from a binomial distribution.
"""
self._not_implemented_yet("binomial")
[docs]
def chisquare(self, df, size=None):
"""
Draw samples from a chi-square distribution.
"""
self._not_implemented_yet("chisquare")
[docs]
def dirichlet(self, alpha, size=None):
"""
Draw samples from the Dirichlet distribution.
"""
self._not_implemented_yet("dirichlet")
[docs]
def exponential(self, scale=1.0, size=None):
"""
Draw samples from an exponential distribution.
"""
self._not_implemented_yet("exponential")
[docs]
def f(self, dfnum, dfden, size=None):
"""
Draw samples from an F distribution.
"""
self._not_implemented_yet("f")
[docs]
def gamma(self, shape, scale=1.0, size=None):
"""
Draw samples from a Gamma distribution.
"""
self._not_implemented_yet("gamma")
[docs]
def geometric(self, p, size=None):
"""
Draw samples from the geometric distribution.
"""
self._not_implemented_yet("geometric")
[docs]
def gumbel(self, loc=0.0, scale=1.0, size=None):
"""
Draw samples from a Gumbel distribution.
"""
self._not_implemented_yet("gumbel")
[docs]
def hypergeometric(self, ngood, nbad, nsample, size=None):
"""
Draw samples from a Hypergeometric distribution.
"""
self._not_implemented_yet("hypergeometric")
[docs]
def laplace(self, loc=0.0, scale=1.0, size=None):
"""
Draw samples from the Laplace or double exponential distribution with specified location (or mean=0.0) and scale (decay).
"""
self._not_implemented_yet("laplace")
[docs]
def logistic(self, loc=0.0, scale=1.0, size=None):
"""
Draw samples from a logistic distribution.
"""
self._not_implemented_yet("logistic")
[docs]
def lognormal(self, mean=0.0, sigma=1.0, size=None):
"""
Draw samples from a log-normal distribution.
"""
self._not_implemented_yet("lognormal")
[docs]
def logseries(self, p, size=None):
"""
Draw samples from a logarithmic series distribution.
"""
self._not_implemented_yet("logseries")
[docs]
def multinomial(self, n, pvals, size=None):
"""
Draw samples from a multinomial distribution.
"""
self._not_implemented_yet("multinomial")
[docs]
def multivariate_normal(self, mean, cov, size=None):
"""
Draw random samples from a multivariate normal distribution.
"""
self._not_implemented_yet("multivariate_normal")
[docs]
def negative_binomial(self, n, p, size=None):
"""
Draw samples from a negative binomial distribution.
"""
self._not_implemented_yet("negative_binomial")
[docs]
def noncentral_chisquare(self, df, nonc, size=None):
"""
Draw samples from a noncentral chi-square distribution.
"""
self._not_implemented_yet("noncentral_chisquare")
[docs]
def noncentral_f(self, dfnum, dfden, nonc, size=None):
"""
Draw samples from the noncentral F distribution.
"""
self._not_implemented_yet("noncentral_f")
[docs]
def normal(self, loc=0.0, scale=1.0, size=None):
"""
Draw random samples from a normal (Gaussian) distribution.
"""
self._not_implemented_yet("normal")
[docs]
def pareto(self, a, size=None):
"""
Draw samples from a Pareto II or Lomax distribution with specified shape.
"""
self._not_implemented_yet("pareto")
[docs]
def poisson(self, lam, size=None):
"""
Draw samples from a Poisson distribution.
"""
self._not_implemented_yet("poisson")
[docs]
def rayleigh(self, scale=1.0, size=None):
"""
Draw samples from a Rayleigh distribution.
"""
self._not_implemented_yet("rayleigh")
[docs]
def standard_cauchy(self, size=None):
"""
Draw samples from a standard Cauchy distribution with mode = 0.
"""
self._not_implemented_yet("standard_cauchy")
[docs]
def standard_exponential(self, size=None):
"""
Draw samples from the standard exponential distribution.
"""
self._not_implemented_yet("standard_exponential")
[docs]
def standard_gamma(self, shape, size=None):
"""
Draw samples from a standard Gamma distribution.
"""
self._not_implemented_yet("standard_gamma")
[docs]
def standard_normal(self, size=None):
"""
Draw samples from a standard Normal distribution (mean=0.0, stdev=1).
"""
self._not_implemented_yet("standard_normal")
[docs]
def standard_t(self, df, size=None):
"""
Draw samples from a standard Student's t distribution with df degrees of freedom.
"""
self._not_implemented_yet("standard_t")
[docs]
def triangular(self, left, mode, right, size=None):
"""
Draw samples from the triangular distribution over the interval left, right.
"""
self._not_implemented_yet("triangular")
[docs]
def vonmises(self, mu, kappa, size=None):
"""
Draw samples from a von Mises distribution.
"""
self._not_implemented_yet("vonmises")
[docs]
def wald(self, mean=0.0, scale=1.0, size=None):
"""
Draw samples from a Wald, or inverse Gaussian, distribution.
"""
self._not_implemented_yet("wald")
[docs]
def weibull(self, a, size=None):
"""
Draw samples from a Weibull distribution.
"""
self._not_implemented_yet("weibull")
[docs]
def zipf(self, a, size=None):
"""
Draw samples from a Zipf distribution.
"""
self._not_implemented_yet("zipf")
# Random generator
[docs]
def seed(self, seed=None):
"""
Seed the generator.
"""
self._not_implemented_yet("seed")
[docs]
def get_state(self):
"""
Return a tuple representing the internal state of the generator.
"""
self._not_implemented_yet("get_state")
[docs]
def set_state(self, state):
"""
Set the internal state of the generator from a tuple.
"""
self._not_implemented_yet("set_state")
################
# SET ROUTINES #
# See https://docs.scipy.org/doc/numpy/reference/routines.set.html
# Making proper sets
[docs]
def unique(self, ar, return_index=False, return_inverse=False, return_counts=False):
"""
Find the unique elements of an array.
"""
self._not_implemented_yet("unique")
# Boolean operations
[docs]
def in1d(self, ar1, ar2, assume_unique=False, invert=False):
"""
Test whether each element of a 1-D array is also present in a second array.
"""
self._not_implemented_yet("in1d")
[docs]
def intersect1d(self, ar1, ar2, assume_unique=False):
"""
Find the intersection of two arrays.
"""
self._not_implemented_yet("intersect1d")
[docs]
def setdiff1d(self, ar1, ar2, assume_unique=False):
"""
Find the set difference of two arrays.
"""
self._not_implemented_yet("setdiff1d")
[docs]
def setxor1d(self, ar1, ar2, assume_unique=False):
"""
Find the set exclusive-or of two arrays.
"""
self._not_implemented_yet("setxor1d")
[docs]
def union1d(self, ar1, ar2):
"""
Find the union of two arrays.
"""
self._not_implemented_yet("union1d")
###################################
# SORTING, SEARCHING AND COUNTING #
# See https://docs.scipy.org/doc/numpy/reference/routines.sort.html
# Sorting
[docs]
def sort(self, a, axis=-1, kind="quicksort", order=None):
"""
Return a sorted copy of an array.
"""
self._not_implemented_yet("sort")
[docs]
def lexsort(self, keys, axis=-1):
"""
Perform an indirect sort using a sequence of keys.
"""
self._not_implemented_yet("lexsort")
[docs]
def argsort(self, a, axis=-1, kind="quicksort", order=None):
"""
Returns the indices that would sort an array.
"""
self._not_implemented_yet("argsort")
[docs]
def msort(self, a):
"""
Return a copy of an array sorted along the first axis.
"""
self._not_implemented_yet("msort")
[docs]
def sort_complex(self, a):
"""
Sort a complex array using the real part first, then the imaginary part.
"""
self._not_implemented_yet("sort_complex")
[docs]
def partition(self, a, kth, axis=-1, kind="quicksort", order=None):
"""
Return a partitioned copy of an array.
"""
self._not_implemented_yet("partition")
[docs]
def argpartition(self, a, kth, axis=-1, kind="quicksort", order=None):
"""
Perform an indirect partition along the given axis using the algorithm specified by the kind keyword.
"""
self._not_implemented_yet("argpartition")
# Searching
[docs]
def argmax(self, a, axis, out=None):
"""
Returns the indices of the maximum values along an axis.
"""
self._not_implemented_yet("argmax")
[docs]
def nanargmax(self, a, axis=None):
"""
Return the indices of the maximum values in the specified axis ignoring NaNs.
"""
self._not_implemented_yet("nanargmax")
[docs]
def argmin(self, a, axis, out=None):
"""
Returns the indices of the minimum values along an axis.
"""
self._not_implemented_yet("argmin")
[docs]
def nanargmin(self, a, axis=None):
"""
Return the indices of the minimum values in the specified axis ignoring NaNs.
"""
self._not_implemented_yet("nanargmin")
[docs]
def argwhere(self, a):
"""
Find the indices of array elements that are non-zero, grouped by element.
"""
self._not_implemented_yet("argwhere")
[docs]
def nonzero(self, a):
"""
Return the indices of the elements that are non-zero.
"""
self._not_implemented_yet("nonzero")
[docs]
def flatnonzero(self, a):
"""
Return indices that are non-zero in the flattened version of a.
"""
self._not_implemented_yet("flatnonzero")
[docs]
def where(self, condition, x, y):
"""
Return elements, either from x or y, depending on condition.
"""
self._not_implemented_yet("where")
[docs]
def searchsorted(self, a, v, side="left", sorter=None):
"""
Find indices where elements should be inserted to maintain order.
"""
self._not_implemented_yet("searchsorted")
# Counting
[docs]
def count_nonzero(self, a, axis=None):
"""
Counts the number of non-zero values in the array a.
"""
self._not_implemented_yet("count_nonzero")
##############
# STATISTICS #
# See https://docs.scipy.org/doc/numpy/reference/routines.sort.html
# Order statistics
[docs]
def amin(self, a, axis=None, out=None):
"""
Return the minimum of an array or minimum along an axis.
"""
self._not_implemented_yet("amin")
[docs]
def amax(self, a, axis=None, out=None):
"""
Return the maximum of an array or maximum along an axis.
"""
self._not_implemented_yet("amax")
[docs]
def nanmin(self, a, axis=None, out=None):
"""
Return minimum of an array or minimum along an axis, ignoring any NaNs.
"""
self._not_implemented_yet("nanmin")
[docs]
def nanmax(self, a, axis=None, out=None):
"""
Return the maximum of an array or maximum along an axis, ignoring any NaNs.
"""
self._not_implemented_yet("nanmax")
[docs]
def ptp(self, a, axis=None, out=None):
"""
Range of values (maximum - minimum) along an axis.
"""
self._not_implemented_yet("ptp")
[docs]
def percentile(
self, a, q, axis=None, out=None, overwrite_input=False, interpolation="linear"
):
"""
Compute the qth percentile of the data along the specified axis.
"""
self._not_implemented_yet("percentile")
[docs]
def nanpercentile(
self, a, q, axis=None, out=None, overwrite_input=False, interpolation="linear"
):
"""
Compute the qth percentile of the data along the specified axis,
while ignoring nan values.
"""
self._not_implemented_yet("nanpercentile")
# Averages and variances
[docs]
def average(self, a, axis=None, weights=None, returned=False):
"""
Compute the weighted average along the specified axis.
"""
self._not_implemented_yet("average")
[docs]
def mean(self, a, axis=None, dtype=None, out=None):
"""
Compute the arithmetic mean along the specified axis.
"""
self._not_implemented_yet("mean")
[docs]
def std(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the standard deviation along the specified axis.
"""
self._not_implemented_yet("std")
[docs]
def var(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the variance along the specified axis.
"""
self._not_implemented_yet("var")
[docs]
def nanmean(self, a, axis=None, dtype=None, out=None):
"""
Compute the arithmetic mean along the specified axis, ignoring NaNs.
"""
self._not_implemented_yet("nanmean")
[docs]
def nanstd(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the standard deviation along the specified axis, while ignoring NaNs.
"""
self._not_implemented_yet("nanstd")
[docs]
def nanvar(self, a, axis=None, dtype=None, out=None, ddof=0):
"""
Compute the variance along the specified axis, while ignoring NaNs.
"""
self._not_implemented_yet("nanvar")
# Correlating
[docs]
def corrcoef(self, x, y, rowvar=1):
"""
Return Pearson product-moment correlation coefficients.
"""
self._not_implemented_yet("corrcoef")
[docs]
def correlate(self, a, v, mode="valid"):
"""
Cross-correlation of two 1-dimensional sequences.
"""
self._not_implemented_yet("correlate")
[docs]
def cov(
self,
m,
y=None,
rowvar=True,
bias=False,
ddof=None,
fweights=None,
aweights=None,
):
"""
Estimate a covariance matrix, given data and weights.
"""
self._not_implemented_yet("cov")
# Histograms
[docs]
def histogram(
self, a, bins=10, range=None, normed=False, weights=None, density=None
):
"""
Compute the histogram of a set of data.
"""
self._not_implemented_yet("histogram")
[docs]
def histogram2d(self, x, y, bins, range=None, normed=False, weights=None):
"""
Compute the bi-dimensional histogram of two data samples.
"""
self._not_implemented_yet("histogram2d")
[docs]
def histogramdd(self, sample, bins, range=None, normed=False, weights=None):
"""
Compute the multidimensional histogram of some data.
"""
self._not_implemented_yet("histogramdd")
[docs]
def bincount(self, x, weights=None, minlength=None):
"""
Count number of occurrences of each value in array of non-negative ints.
"""
self._not_implemented_yet("bincount")
[docs]
def digitize(self, x, bins, right=False):
"""
Return the indices of the bins to which each value in input array belongs.
"""
self._not_implemented_yet("digitize")
###############
### ALIASES ###
[docs]
def degrees(self, x, out=None, **kargs):
"""
Convert angles from radians to degrees.
"""
return self.rad2deg(x=x, out=out, **kargs)
[docs]
def radians(self, x, out=None, **kargs):
"""
Convert angles from degrees to radians.
"""
return self.deg2rad(x=x, out=out, **kargs)
[docs]
def remainder(self, x1, x2, out=None, **kargs):
"""
Return element-wise remainder of division (MOD).
Remainder has the same sign as the divisor x2.
match Python modfulus operator x1 % x2.
Returns x - y*floor(x/y)
"""
return self.mod(x1=x1, x2=x2, out=out, **kargs)
##########################
### EXTRA HYSOP METHODS ##
def __generate_hysop_type_functions():
functions = {
"as{type}array": '''
def hysop_array_generated_method(self, a, order=default_order, **kargs):
"""
Convert the input to an array of dtype HYSOP_{TYPE}.
"""
dtype = HYSOP_{TYPE}
return self.asarray(a=a, dtype=dtype, order=order, **kargs)
''',
"{type}_prod": '''
def hysop_array_generated_method(self, a, axis=None, out=None, **kargs):
"""
Sum of array elements over a given axis.
"""
dtype = HYSOP_{TYPE}
return self.prod(a=a,axis=axis,out=out,dtype=dtype,**kargs)
''',
"{type}_sum": '''
def hysop_array_generated_method(self, a, axis=None, out=None, **kargs):
"""
Sum of array elements over a given axis.
"""
dtype = HYSOP_{TYPE}
return self.sum(a=a,axis=axis,out=out,dtype=dtype,**kargs)
''',
"{type}_empty": '''
def hysop_array_generated_method(self, shape, order=default_order, **kargs):
"""
Return a new array of given shape and type, without initializing entries.
"""
dtype = HYSOP_{TYPE}
return self.empty(shape=shape, dtype=dtype, order=order, **kargs)
''',
"{type}_ones": '''
def hysop_array_generated_method(self, shape, order=default_order, **kargs):
"""
Return a new array of given shape filled with ones of type HYSOP_{TYPE}.
"""
dtype = HYSOP_{TYPE}
return self.ones(shape=shape, order=order, dtype=dtype, **kargs)
''',
"{type}_zeros": '''
def hysop_array_generated_method(self, shape, order=default_order, **kargs):
"""
Return a new array of given shape, filled with zeros of type HYSOP_{TYPE}.
"""
dtype = HYSOP_{TYPE}
return self.zeros(shape=shape, order=order, dtype=dtype, **kargs)
''',
"{type}_full": '''
def hysop_array_generated_method(self, shape, fill_value, order=default_order, **kargs):
"""
Return a new array of given shape, filled with fill_value of type HYSOP_{TYPE}.
"""
dtype = HYSOP_{TYPE}
return self.full(shape=shape, fill_value=filling_value, order=order, dtype=dtype, **kargs)
''',
}
hysop_types = ["real", "complex", "integer", "index", "dim", "bool"]
for ht in hysop_types:
for fname, fdefinition in functions.items():
fname = fname.format(type=ht, TYPE=ht.upper())
fdef = """
from hysop.constants import default_order, MemoryOrdering, Backend
from hysop.constants import HYSOP_REAL, HYSOP_COMPLEX, HYSOP_ORDER
from hysop.constants import HYSOP_INTEGER, HYSOP_INDEX, HYSOP_DIM, HYSOP_BOOL
{}
""".format(
fdefinition.format(type=ht, TYPE=ht.upper())
)
namespace = dict()
exec(fdef, namespace)
setattr(ArrayBackend, fname, namespace["hysop_array_generated_method"])
__generate_hysop_type_functions()